//  我的订单
//  OrdersViewController.m
//  GoBigMarket
//
//  Created by 李真 on 16/8/21.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "OrdersViewController.h"
#import "OrdersTableViewCell.h"
#import "DetailOrderViewController.h"
#import "OrdersModel.h"
#import "BeeCloud.h"
static NSString *state;//记录状态
@interface OrdersViewController ()<BeeCloudDelegate>{
    
}
@property (nonatomic,strong)DetailOrderViewController *detailOrderVC;
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)MJRefreshNormalHeader *header;
@end

@implementation OrdersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    state = @"1";
    self.tableView.hidden = YES;
    //解决tableView偏移
    self.automaticallyAdjustsScrollViewInsets = false;
    [self.tableView setContentInset:UIEdgeInsetsMake(-25, 0, 0, 0)];
    self.navigationItem.title = @"我的订单";
    
    if (!self.dataArr) {
        self.dataArr = [NSMutableArray array];
    }
    
    self.allBtn.selected = YES;
    self.ingBtn.selected = NO;
    
    self.backView.layer.masksToBounds = YES;
    self.backView.layer.cornerRadius = 1;
    
    [self.allBtn setTitleColor:GDJGreenColor forState:UIControlStateSelected];
    [self.allBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [self.ingBtn setTitleColor:GDJGreenColor forState:UIControlStateSelected];
    [self.ingBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //下拉刷新
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshingData)];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
      _header.automaticallyChangeAlpha = YES;
    
    // 隐藏时间
//    _header.lastUpdatedTimeLabel.hidden = YES;
    
    // 马上进入刷新状态
//    [self.header beginRefreshing];
    // 设置header
    self.tableView.mj_header = self.header;
}

#pragma mark - 生命周期
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [BeeCloud setBeeCloudDelegate:self];
    self.tabBarController.tabBar.hidden = YES;
    [self netWorkingWithState];
    
    //开启通知,用于刷新页面
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netWorkingWithState) name:@"QuXiaoDingDan" object:nil];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear: animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"QuXiaoDingDan" object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [self.header endRefreshing];
}
#pragma mark - 网络请求
//第一次请求
- (void)netWorkingWithState{
    [self SVProgressHUDAction];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [CQNetWorkTools GETWithURL:GetMyOrders par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"SFAll":state} success:^(id responseObject) {
        DLog(@"订单列表： %@",responseObject);
        if ([[responseObject valueForKey:@"Err"]integerValue] != 0) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }else{
            
        [self.dataArr removeAllObjects];
        self.dataArr = [OrdersModel mj_objectArrayWithKeyValuesArray:[responseObject valueForKey:@"Orders"]];
        self.tableView.hidden = NO;
        [SVProgressHUD dismiss];
        [self.tableView reloadData];
        }
//        NSLog(@"end");
    } filed:^(NSError *error) {
//        NSLog(@"error :%@",error);
        [SVProgressHUD dismiss];
    }];
}

//刷新请求
-  (void)refreshingData{
    [self.header beginRefreshing];
    [self SVProgressHUDAction];
    
    [CQNetWorkTools GETWithURL:GetMyOrders par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"SFAll":state} success:^(id responseObject) {
        DLog(@"订单列表： %@",responseObject);
        if ([[responseObject valueForKey:@"Err"]integerValue] != 0) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }else{
            [self.dataArr removeAllObjects];
            self.dataArr = [OrdersModel mj_objectArrayWithKeyValuesArray:[responseObject valueForKey:@"Orders"]];
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }
        
        [SVProgressHUD dismiss];
        [self.header endRefreshing];
    } filed:^(NSError *error) {
        [self.header endRefreshing];
        [SVProgressHUD dismiss];
    }];
}
#pragma mark - SVProgressHUD
- (void)SVProgressHUDAction{
    //渐变而且禁止用户操作
//    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
}

#pragma mark - "全部"按钮触发
- (IBAction)allBtnAction:(id)sender {
    DLog(@"1");
    self.allBtn.selected = YES;
    self.ingBtn.selected = NO;
    [UIView animateWithDuration:.25 animations:^{
        self.backView.left = 0;
    }];
    state = @"1";
    [self netWorkingWithState];
}
#pragma mark - "进行中"按钮触发
- (IBAction)ingBtnAction:(id)sender {
    DLog(@"0");
    self.allBtn.selected = NO;
    self.ingBtn.selected = YES;
    [UIView animateWithDuration:.25 animations:^{
        self.backView.left = self.allBtn.right;
    }];
    state = @"0";
    [self netWorkingWithState];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.dataArr.count > 0) {
        return self.dataArr.count;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OrdersTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderCell"];
    if (!cell) {

        cell = [[[NSBundle mainBundle]loadNibNamed:@"OrdersTableViewCell" owner:self options:nil]lastObject];
    }
    cell.model = self.dataArr[indexPath.section];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 230;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    OrdersModel *model = self.dataArr[indexPath.section];
    if (!_detailOrderVC) {
        _detailOrderVC = [[DetailOrderViewController alloc]init];
    }
    _detailOrderVC.orderId = model.Id;
    _detailOrderVC.state = [model.OrderStatus intValue];            //传状态
    [self.navigationController pushViewController:_detailOrderVC animated:YES];
}
#pragma mark - 微信支付回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    
    switch (resp.type) {
        case BCObjsTypePayResp:
        {
            
            // 支付请求响应
            BCPayResp *tempResp = (BCPayResp *)resp;
            if (tempResp.resultCode == 0) {
                BCPayReq *payReq = (BCPayReq *)resp.request;
                //百度钱包比较特殊需要用户用获取到的orderInfo，调用百度钱包SDK发起支付
                if (payReq.channel == PayChannelBaiduApp && ![BeeCloud getCurrentMode]) {
                    
                } else {
                    //微信、支付宝、银联支付成功
                    self.tabBarController.selectedIndex = 0;
                }
            } else {
                //支付取消或者支付失败
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryBillsResp:
        {
            
            BCQueryBillsResp *tempResp = (BCQueryBillsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [self showAlertView:@"未找到相关订单信息"];
                } else {
                    
                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryRefundsResp:
        {
            
            BCQueryRefundsResp *tempResp = (BCQueryRefundsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [self showAlertView:@"未找到相关订单信息"];
                } else {
                    
                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        default:
        {
            if (resp.resultCode == 0) {
                [self showAlertView:resp.resultMsg];
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",resp.resultMsg, resp.errDetail]];
            }
        }
            break;
    }
}
- (void)showAlertView:(NSString *)msg {
    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

@end
